package net.qiqb.subclass;

import cn.hutool.json.JSONUtil;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class ByteBuddyAgentExample {

    public static void premain(String agentArgs, Instrumentation instrumentation) {
        new AgentBuilder.Default()
                .type(ElementMatchers.named("net.qiqb.subclass.OrderDto"))
                .transform(new OrderTransformer())
                .installOn(instrumentation);
    }

    public static class OrderTransformer implements AgentBuilder.Transformer {

        @Override
        public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, ProtectionDomain protectionDomain) {
            return builder.method(ElementMatchers.named("newInstance")).intercept(Advice.to(SubOrderInterceptor.class));
        }
    }

    public static class SubOrderInterceptor {

        @Advice.OnMethodExit
        public static void onExit(@Advice.Origin Object obj, @Advice.Return  Object re) {
            System.out.println("eeee"+obj);
            System.out.println("22"+re);
            if (obj .getClass().getName().equals("net.qiqb.subclass.OrderDto")) {
                // 在构造器中，你可以使用 @Advice.This 访问正在构造的对象

                OrderDto originalOrder = (OrderDto) obj;
                // 创建 SubOrder 对象
                SubOrder subOrder = new SubOrder("123");
                // 在这里，你可以对 subOrder 进行一些额外的初始化操作
                // 替换正在构造的对象
               //re = subOrder;
            }
        }



    }

    public static void main(String[] args) {
        final Instrumentation install = ByteBuddyAgent.install();
        premain(null, install);
        OrderDto o = OrderDto.newInstance("ces");
        o.setNo("ces");
        System.out.println(o.getId());
    }
}
